#include "conn.h"
#include "ds_proto.h"
#include "task.h"
#include "util.h"

enum READ_STATUS CliConn::OnRead() {
  struct evbuffer *in_buf = get_input_buffer();
  int64_t in_buf_size = evbuffer_get_length(in_buf);
  
  if (in_buf_size <= 0)
    return READ_BAD_CLIENT;

  if (in_buf_size < sizeof(TrackerHeader))
    return READ_NEED_MORE_DATA; 
 
  TrackerHeader *header = (TrackerHeader *)evbuffer_pullup(in_buf,
      sizeof(TrackerHeader));
  if (header == NULL)
    return READ_INNER_ERROR;

  int64_t pkg_len = Util::buff2long(header->pkg_len);
  if (pkg_len < 0)
    return READ_BAD_CLIENT;

  if (in_buf_size < sizeof(TrackerHeader) + pkg_len) 
    return READ_NEED_MORE_DATA;

  DSTask *task = new DSTask();
  if (task == NULL)
    return READ_INNER_ERROR;
 
  LOG_DEBUG("read trackheader->pkg_len:%d, cmd:%d, status:%d",
            pkg_len, header->cmd, header->status);
  
  if (!task->Init(this, in_buf, sizeof(TrackerHeader) + pkg_len)) {
    delete task;
    return READ_INNER_ERROR;
  }

  DisableRead();

  g_work_thread_pool->CallInThread(DSTask::PerformDefferCb, task);
  return READ_ALL_DATA;
}


